﻿using Apps.Common;
using Apps.IBLL;
using Apps.Models;
using Unity;
using System;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Security;
using Apps.Models.Sys;
using Apps.Models.Common;
using Apps.IBLL.Sys;
using Apps.WebApi.Core;
using Apps.Core;
using Apps.DAL.Sys;
using System.Globalization;
using System.Threading;
using Apps.Locale;
using System.Net.Http;
using Apps.WebApi.Models;

namespace Apps.WebApi.Controllers
{
    /// <summary>
    /// 用户登陆
    /// </summary>
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class AccountController : ApiController
    {
        /// <summary>
        /// 登录
        /// </summary>
        [Dependency]
        public IAccountBLL accountBLL { get; set; }
        [Dependency]
        public ISysUserBLL sysUserBLL { get; set; }

        /// <summary>
        /// 令牌
        /// </summary>
        [Dependency]
        public ISysValidTokenBLL tokenBLL { get; set; }

        /// <summary>
        /// 用户
        /// </summary>
        [Dependency]
        public ISysUserBLL sysuser_BLL { get; set; }

        ValidationErrors errors = new ValidationErrors();

        #region 10.10 管理员登陆
        /// <summary>
        /// 管理员登陆
        /// </summary>
        /// <param name="postModel">userName：登录账号<br/>password：登陆密码</param>
        /// <returns>用户信息与Token</returns>
        [HttpPost]
        public HttpResponseMessage LoginSys([FromBody]LoginModel postModel)
        {
            SysUserModel user = accountBLL.Login(postModel.userName, ValueConvert.MD5(postModel.password));
            if (user == null)
            {
                return CoreCommon.toJson(JsonHandler.CreateMessage(0, "用户名或密码错误"));
            }
            else if (!Convert.ToBoolean(user.State))//被禁用
            {
                return CoreCommon.toJson(JsonHandler.CreateMessage(0, "账户被系统禁用"));
            }
            //更见简洁的加密
            var Token = DESEncrypt.Encrypt(string.Format("{0}&{1}", user.Id, DateTime.Now.ToString("yyyyMMddHHmmssfffffff")));
         
            //将身份信息保存在session中，验证当前请求是否是有效请求
            //HttpContext.Current.Session[userName] = Token;

            SysValidTokenModel tokenModel = new SysValidTokenModel();
            tokenModel.Id = user.Id;
            tokenModel.Token = Token;
            tokenModel.OverTime = ResultHelper.NowTime.AddDays(7);
            tokenModel.CreateTime = ResultHelper.NowTime;
            if (tokenBLL.Create(ref errors, tokenModel))
            {
                //将Token保存在数据库中有效期为7天
                return CoreCommon.toJson(JsonHandler.CreateMessage(1, Token));
            }
            else
            {
                return CoreCommon.toJson(JsonHandler.CreateMessage(0, errors.Error));
            }
        }
        #endregion

      
     
    }
}
